package com.mlethe.library.multi.demo;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.mlethe.library.multi.api.MultiApi;
import com.mlethe.library.multi.api.MultiMedia;
import com.mlethe.library.multi.api.PayAction;
import com.mlethe.library.multi.api.listener.OnActionListener;
import com.mlethe.library.multi.demo.databinding.ActivityPayBinding;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Map;

/**
 * 支付
 */
public class PayActivity extends AppCompatActivity {

    private ActivityPayBinding binding;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityPayBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        OnActionListener listener = new OnActionListener() {
            @Override
            public void onComplete(@NonNull MultiMedia media, @NonNull Map<String, String> map) {
                Log.e("multi", "onComplete: " + media + ", map->" + map);
                Toast.makeText(PayActivity.this, media + "支付完成：" + map, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancel(@NonNull MultiMedia media) {
                Log.e("multi", "onCancel: " + media);
                Toast.makeText(PayActivity.this, media + "支付取消", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(@NonNull MultiMedia media, int code, String msg) {
                Log.e("multi", "onFailure: " + media + "，code:" + code + ", msg: " + msg);
                Toast.makeText(PayActivity.this, media + "支付失败，code:" + code + ", msg: " + msg, Toast.LENGTH_SHORT).show();
            }
        };
        binding.wechatPayBtn.setOnClickListener(v -> {
            new PayAction(MultiMedia.WECHAT)
                    .setAppId("wxc4c3b31e592dc8c2")
                    .setMerchantId("1523339171")
                    .setPrepayId("wx1912544231056440112b20081394401800")
                    .setPackageValue("Sign=WXPay")
                    .setNonceStr("1579409684000")
                    .setTimeStamp(1579409684)
                    .setSign("C61B6784BF9BA76C427FFA22DDA06178")
                    .setExtData("")
                    .setCallback(listener)
                    .pay(this);
        });
        binding.alipayPayBtn.setOnClickListener(v -> {
            new PayAction(MultiMedia.ALIPAY)
                    .setOrderInfo("alipay_sdk=alipay-sdk-java-3.7.4.ALL&app_id=2016101000649179&biz_content={\\\"body\\\":\\\"我是测试数据\\\",\\\"out_trade_no\\\":\\\"20190730\\\",\\\"product_code\\\":\\\"QUICK_MSECURITY_PAY\\\",\\\"subject\\\":\\\"App支付测试Java\\\",\\\"timeout_express\\\":\\\"30m\\\",\\\"total_amount\\\":\\\"0.01\\\"}&charset=utf-8&format=json&method=alipay.trade.app.pay&sign=Z+etI84SIyhKOMzKVWDsGK0uAG+cn3O476zvwdVKMdiblkAIvhIUseeGoqvyLnsKxP62aW5J3D5s258kJQWfyHt7wA/b0jL8oe8i9LjAjrOTZFuX2AIkKa2TbyX96uQt2BY5oFDS6W564QOxL+0QqA1GqfsInaBKaJiuBZFhJ5924Wh4BnHS3X6abetAKyCVp+2oVI1NAuq7CwcILHS59YhhGfim6lMgbyVi7Y2o/s/UYpY03nzpL6FXqhZz87mxWXvxCgSZkUgDfzleVf3pQgtSNKjDCR5OIVAZHw+QlrrabDI7Hglbc9syZmSNUlgYzzqyownkLAk7vEzKY35lmQ==&sign_type=RSA2×tamp=2019-07-30 16:04:16&version=1.0")
                    .setCallback(listener)
                    .pay(this);
        });
        binding.alipayQrBtn.setOnClickListener(v -> {
            String url = "https://qr.alipay.com/bax03816sgyopjpdbd0p4054";
            String encoderUrl = null;
            try {
                encoderUrl = URLEncoder.encode(url, "UTF-8");
            } catch (Exception e) {
                e.printStackTrace();
            }
            new PayAction(MultiMedia.ALIPAY)
                    .setQrcode(encoderUrl)
                    .setCallback(listener)
                    .pay(this);
        });
        binding.alipayUrlBtn.setOnClickListener(v -> {
            String url = "";
            String encoderUrl = null;
            try {
                encoderUrl = URLEncoder.encode(url, "UTF-8");
            } catch (Exception e) {
                e.printStackTrace();
            }
            new PayAction(MultiMedia.ALIPAY)
                    .setUrl(encoderUrl)
                    .setCallback(listener)
                    .pay(this);
        });
        binding.alipaySigningBtn.setOnClickListener(v -> {
            String url = "https://openapi.alipaydev.com/gateway.do?alipay_sdk=alipay-sdk-java-3.7.4.ALL&app_id=2016101000649179&charset=utf-8&format=json&method=zhima.customer.certification.certify&sign=OQLDh10SyprbFlicgqwhrUK73F2pDkj0DhZdQnOnBQ%2FPDGpLXiRYOVXUbPtUr6MwgiLmR8vlNZCALqSx5%2Fcl81wdD6fQJ9vBZjUei%2Ffd%2Buu5eXqSj8RCK5qFMRE4zvFRrdBhuI8fXlsP%2FpTYxocddxRPlbFxh%2B2KmMpb3p%2BTrqmdyWbBsvvgjZfgtSOHn61%2FjLYge1Yndwj4pMW%2B%2FWUGeH6s9eOOQw3eu%2Bh7bm7na5ayLCN9l2aaCHkDhxulmBya8jaTxZ0vitJilPtVdCxVa%2B%2BfLdj%2F%2FV%2BmShW5L8oxzURRk5%2F%2BpwLXkL0COmuqAXEYZIxSc6gaOoBDuZc90bPpvg%3D%3D&sign_type=RSA2×tamp=2019-08-22+14%3A47%3A39&version=1.0";
            String encoderUrl = null;
            try {
                encoderUrl = URLEncoder.encode(url, "UTF-8");
            } catch (Exception e) {
                e.printStackTrace();
            }
            new PayAction(MultiMedia.ALIPAY)
                    .setSigningLink(encoderUrl)
                    .setCallback(listener)
                    .pay(this);
        });
        binding.unionPayBtn.setOnClickListener(v -> {
            unionPay(listener);
        });
        binding.qqPayBtn.setOnClickListener(v -> {
            new PayAction(MultiMedia.QQ_PAY)
                    .setAppId("")
                    .setMerchantId("")
                    .setSerialNumber("")
                    .setPrepayId("")
                    .setCallbackScheme("")
                    .setPubAcc("")
                    .setPubAccHint("")
                    .setTimeStamp(0)
                    .setNonceStr("")
                    .setSignType("HMAC-SHA1")
                    .setSign("")
                    .setCallback(listener)
                    .pay(this);
        });
        binding.googleBtn.setOnClickListener(v -> {
            new PayAction(MultiMedia.GOOGLE)
                    .setProductId("xxxx")
                    .setObfuscatedAccountId("obfuscatedAccountId")
                    .setCallback(listener)
                    .pay(this);
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        MultiApi.getInstance().onActivityResult(this, requestCode, resultCode, data);
    }

    /**
     * 云闪付支付
     */
    private void unionPay(OnActionListener listener) {
        new Thread(() -> {
            String tn = null;
            InputStream is;
            try {

                String url = "http://101.231.204.84:8091/sim/getacptn";

                URL myURL = new URL(url);
                URLConnection ucon = myURL.openConnection();
                ucon.setConnectTimeout(120000);
                is = ucon.getInputStream();
                int i = -1;
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                while ((i = is.read()) != -1) {
                    baos.write(i);
                }

                tn = baos.toString();
                is.close();
                baos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            String finalTn = tn;
            Log.e("multi", "unionPay: " + finalTn);
            new PayAction(MultiMedia.UNION_PAY)
                    .setMerchantId("")
                    .setTn(finalTn)
                    .setCallback(listener)
                    .pay(this);
        }).start();
    }

    @Override
    protected void onResume() {
        super.onResume();
        MultiApi.getInstance().resume();
    }
}
